<template>
	<div class="zuoda">
		<div class="question">
			<div class="title">
				<span>{{ questIndex }}.简答题</span>
			</div>
			<div class="question">
				<template v-for="(item,index) in question.quest.question[0].value" :key="index">
					<p class="bigDesc" v-if="item !==''" dir="auto">
						{{ item }}
					</p>
				</template>

				<template v-for="(item1,index1) in question.quest.subQuestion[0].question" :key="index1">
					<template v-if="item1.type ==='text'">
						<template v-for="(item,index) in item1.value" :key="index">
							<p dir="auto">
								{{item}}
							</p>
							<div v-if="question.quest.subQuestion[0].subTemplate && question.quest.subQuestion[0].subTemplate === 'Replacement'" class="scoll" >
								<p dir="auto">请按照格式，依次读下列内容</p>
								<div class="scollContent">
									<p dir="auto">
										{{ changeString(item)}}
									</p>
									<div class="scollBox">
										<VueScrollPicker :options="state.option" :model-value="state.modelValue"/>
									</div>
								</div>
							</div>
						</template>
					</template>
					<template v-if="item1.type==='picture'">
						<div class="picture">
							<el-image
								style="width: 150px; height: 150px"
								:src="item1.value"
								fit="contain"
								:preview-src-list="[String(item1.value)]"
								:initial-index="0"
								@click.stop
							/>
						</div>
					</template>
					<template v-if="item1.type==='audio'">
						<div class="source" @click = "handlePlay(item1.value)">
							<img src="@/assets/audio.png" @click="handlePlay(item1.value)">
						</div>
					</template>
					<template v-if="item1.type==='video'">
						<div class="video">
							<video controls width="250">
								<source :src="item1.value" type="video/webm"/>
							</video>
						</div>
					</template>
				</template>


				<div class="answer">
					<div class="text" v-if="answerType().includes('text')">
						<el-input
							v-model="state.textAnswer"
							:rows="2"
							type="textarea"
							placeholder="请输入答案"
							@change="setUserAnswer"
						/>
					</div>
					<div class="audio" v-if="answerType().includes('audio')">
						<span class="option" @click="openDialog('audio',Number(seq))">
							<el-icon><Microphone/></el-icon>
							<div class="tips">点击上传</div>
						</span>
						<div class="content" v-if="state.audioAnswer">
							<span class="audioAnswer"  @click="handlePlay(state.audioAnswer)">
								<el-icon><Headset/></el-icon>
							</span>
							<span class="tips">
								语音答案：
							</span>
						</div>
					</div>

					<div class="picture" v-if="answerType().includes('picture')">
						<span class="option" @click="openDialog('picture',Number(seq))">
							<el-icon><PictureFilled/></el-icon>
							<div class="tips">点击上传</div>
						</span>
						<div class="content picContent" v-if="state.pictureAnswer">
							<span v-if="state.pictureAnswer">
								<el-image
									style="width: 100px; height: 100px"
									:src="state.pictureAnswer"
									fit="contain"
									:preview-src-list="[state.pictureAnswer]"
									:initial-index="0"
									@click.stop
								/>
							</span>
							<span class="tips">
								图片答案：
							</span>
						</div>
					</div>
				</div>
			</div>

		</div>
		<el-dialog
			v-model="state.dialogVisible"
			title="题目作答"
			width="500"
			draggable
			destroy-on-close
			@close="setUserAnswer()"
		>
			<div v-if="state.dialogType === 'audio'">
				<Recoder :questionIndex="seq" :answerIndex="state.answerIndex"></Recoder>
			</div>
			<div v-if="state.dialogType === 'picture'">
				<image-uploader :questionIndex="seq" :answerIndex="state.answerIndex"></image-uploader>
			</div>
			<template #footer>
				<div class="dialog-footer" v-if="state.dialogType!=='writer'">
					<el-button @click="state.dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="setUserAnswer()">
						确定
					</el-button>
				</div>
			</template>
		</el-dialog>

	</div>
</template>
<script setup lang="ts">

import {toRefs, defineProps, reactive, onMounted, PropType, Ref} from 'vue'
import {Headset, Microphone, PictureFilled, Service} from "eleicon";
import {useDataStore} from "@/stores/useDataStore";
import Recoder from "@/components/Recoder/Recoder.vue";
import XieZi from "@/components/questionType/XieZi/XieZi.vue";
import ImageUploader from "@/components/imageUploader/imageUploader.vue";
import Bus from "@/utils/bus";
import {VueScrollPicker} from "vue-scroll-picker";

const props = defineProps({
	//子组件接收父组件传递过来的值
	question: {
		type: Object as PropType<{ quest: {subQuestion: Array<any>,question: Array<any>}, seqNum: number }>,
	},
	questIndex: {
		type: Number
	},
	seq: {
		type: Number
	}
})

const { question,questIndex,seq } = toRefs(props) as { question: Ref<{ quest: { subQuestion: Array<any> ,question: Array<any>}, seqNum: number }>, questIndex: Ref<number>,seq: Ref<number>}
const userAnswerState = useDataStore();


const state = reactive<{
	textAnswer:string,
	audioAnswer:string,
	pictureAnswer:string,
	dialogVisible: boolean,
	dialogType: string,
	answerIndex: number,
	modelValue: string|null,
	option:{value:number,name:string}[]
}>({
		textAnswer: '',
		audioAnswer: '',
		pictureAnswer: '',
		dialogVisible: false,
		dialogType: '',
		answerIndex: 0,
		modelValue: null,
		option: [],
})

const getOptionData = () => {

	if(question?.value?.quest.question[0].value[0] != '替换练习') return;

	state.option = []
	const data = question?.value?.quest.subQuestion[0].constraint.value;
	const row = data.length;
	const col = data[0].length;


	for (let i = 0; i < col; i++) {
		let temp = []
		for (let j = 0; j < row; j++) {
			temp.push(data[j][i])
		}
		state.option.push({
			value: i,
			name: temp.join(' ')
		})
	}

}
onMounted(() => {
	Bus.on('uploadAudio' + seq.value, (data: any) => {
		state.audioAnswer = data.answer
	})
	Bus.on('uploadPicture' + seq.value, (data: any) => {
		state.pictureAnswer = data.answer
	})
	getOptionData();

})
const answerType = () => {
	const typeSet: string[] = question?.value?.quest.subQuestion[0].content.value
	// 代表答案的种类
	let answerType: string[] = [];
	answerType = typeSet.map((item, index) => {
		return item[0];
	})
	return answerType;
}


const getStaticResourceType = (url:string) => {
	const type = url.split('.')[url.split('.').length-1];
	if(['jpg','jpeg','png','gif'].includes(type)){
		return 'picture';
	} else {
		return 'audio';
	}
}

const handlePlay = (source: string) => {
	setUserAnswer();
	if (userAnswerState.currentAudio) {
		userAnswerState.currentAudio.pause(); // 暂停当前音频
		userAnswerState.currentAudio = null; // 释放当前音频
	}

	userAnswerState.currentAudio = new Audio(source) as any; // 创建新的 Audio 对象
	userAnswerState.currentAudio?.play(); // 播放音频
}


const setUserAnswer = () => {
	let answer:{
		text?: string,
		audios?: string[],
		pics?: string[]
	} = {}
	if(state.textAnswer != ''){
		answer.text = state.textAnswer;
	}
	if(state.audioAnswer !=''){
		answer.audios = [getRealUrl(state.audioAnswer)]
	}
	if(state.pictureAnswer != '') {
		answer.pics = [getRealUrl(state.pictureAnswer)]
	}

	const payload = {
		template: question?.value?.quest.subQuestion[0].template,
		userAnswer: [answer]
	};
	userAnswerState.setUserAnswer(payload, seq.value-1);
	state.dialogVisible = false;
	console.log(userAnswerState.userAnswer)
}

const openDialog = (type: string, index: number) => {
	state.dialogType = type;
	state.dialogVisible = true;

}

const changeString = (str: string) => {
	let flag = 0;
	let result = ''
	for (let i = 0; i < str.length; i++) {
		if(flag === 0 && str[i] === '#') {
			result += '（'
			flag = 1;
		} else if(flag === 1 && str[i] ==='#'){
			result += '）'
			flag = 0
		} else {
			result += str[i]
		}
	}

	return result;
}

const getRealUrl = (url:string) => {
	return url.split('/')[url.split('/').length-2]+'/'+url.split('/')[url.split('/').length-1];
}

</script>
<style scoped lang="scss">
.zuoda {
	img {
		width: 30px;
		height: 30px;
		object-fit: contain;
	}

	.question {
		margin-bottom: 20px;

		.title {
			font-size: 20px;
			font-weight: 500;
			margin-bottom: 10px;
			color: #6a727f;
		}

		.dot {
			font-weight: 700;
			color: #5189dd;
			margin-right: 5px;
		}

		.question {
			font-size: 18px;
			color: #7c7787;
			text-indent: 2em;
			.bigDesc {
				margin-bottom: 20px;
			}
			.picture,
			.source,
			.video{
				margin-top: 20px;
				text-indent: 0;
				display: flex;
				justify-content: center;
			}
			.source {
				font-size: 30px;
			}
			.scoll {
				margin-top: 20px;
				.scollContent {
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					text-indent: 0;
					.scollBox {
						width: 30%;
					}
				}
			}



			.iconBox {
				display: flex;
				justify-content: center;
				margin-top: 20px;

				.icon {
					font-size: 30px;
				}

			}

			.answer {
				display: flex;
				flex-direction: column;
				justify-content: center;
				font-size: 30px;
				text-indent: 0;

				.text,
				.audio,
				.picture {
					display: flex;
					flex-direction: column;
					align-items: center;
					text-indent: 0;
					margin-top: 20px;
					.option {
						display: flex;
						flex-direction: column;
						align-items: center;
					}
					.tips {
						font-size: 12px;
					}
				}

				:deep(.el-textarea) {
					width: 90%;
				}
				.content {
					font-size: 15px;
					width: 90%;
					position: relative;
					height: 50px;
					display: flex;
					justify-content: center;
					align-items: center;
					border: 1px solid #dcdfe6;
					text-indent: 0;
					.audioAnswer {
						font-size: 30px;
						cursor: pointer;
					}
					.tips {
						position: absolute;
						left: 0;
						top: 0;
					}
				}
				.picContent {
					height: 120px;
				}

			}
		}

	}

	.option {
		display: flex;
		justify-content: center;
	}
}

</style>